{% load i18n %}
<style>
    .btn-group>.btn+.dropdown-toggle {
        padding-right: 4px;
        padding-left: 4px;
    }

    table.dataTable tbody tr.selected a {
        color: rgb(103, 106, 108);;
    }
</style>

<table class="table table-striped table-bordered table-hover" id="asset_user_list_table" style="width: 100%">
  <thead>
  <tr>
      <th class="text-center">
        <input type="checkbox" id="check_all" class="ipt_check_all" >
      </th>
      <th class="text-center">{% trans 'Hostname' %}</th>
      <th class="text-center">{% trans 'IP' %}</th>
      <th class="text-center">{% trans 'Username' %}</th>
      <th class="text-center">{% trans 'Version' %}</th>
{#      <th class="text-center">{% trans 'Connectivity'%}</th>#}
      <th class="text-center">{% trans 'Datetime' %}</th>
      <th class="text-center">{% trans 'Action' %}</th>
   </tr>
  </thead>
  <tbody>
  </tbody>
</table>
{% include 'assets/_asset_user_auth_update_modal.html' %}
{% include 'assets/_asset_user_auth_view_modal.html' %}
{% include 'authentication/_mfa_confirm_modal.html' %}

<script>
var defaultAssetUserListUrl = "{% url "api-assets:asset-user-list" %}";
var defaultAssetUserDetail = "{% url "api-assets:asset-user-detail" pk=DEFAULT_PK %}";
var assetUserTable;
var defaultNeedPush = false;
var lastMFATime = "{{ request.session.MFA_VERIFY_TIME }}";
var testDatetime = "{% trans 'Test datetime: ' %}";
var mfaVerifyTTL = "{{ SECURITY_MFA_VERIFY_TTL }}";
var mfaNeedCheck = "{{ SECURITY_VIEW_AUTH_NEED_MFA }}" === "True";
var onlyLatestEl = "<span style='padding-right:20px'><input type='checkbox' id='only_latest'> {% trans 'Only latest version' %}</span>";
var onlyLatestChecked = false;
var systemUserId = "";

function initAssetUserTable(option) {
    if (!option) {
        option = {}
    }
    var assetUserListUrl = option.assetUserListUrl || defaultAssetUserListUrl;
    var needPush = option.needPush === undefined ? defaultNeedPush : option.needPush;
    var options = {
        ele: $('#asset_user_list_table'),
        toggle: true,
        columnDefs: [
            {
                targets: 5, createdCell: function (td, cellData) {
                    var data = toSafeLocalDateStr(cellData);
                    $(td).html(data);
                },
            },
            {
                targets: 6, createdCell: function (td, cellData, rowData) {
                    var viewBtn = '<button class="btn btn-xs btn-primary m-l-xs btn-view-auth" DATA>{% trans "View" %}</button>';
                    var updateBtn = '<li><a class="btn-update-auth" DATA>{% trans 'Update' %}</a></li>';
                    var testBtn = '<li><a class="btn-test-auth" DATA>{% trans 'Test' %}</a></li>';
                    var pushBtn = '<li><a class="btn-push-auth" DATA>{% trans 'Push' %}</a></li>';
                    var delBtn = '<li><a class="btn-del-auth" DATA>{% trans 'Delete' %}</a></li>';
                    if (!needPush) {
                        pushBtn = ''
                    }

                    var data = "data-hostname=hostname123 data-username=username123 data-uid=uid123 data-asset=asset123";
                    data = data.replaceAll("username123", rowData.username)
                                     .replaceAll("hostname123", rowData.hostname)
                                     .replaceAll("uid123", rowData.id)
                                     .replaceAll("asset123", rowData.asset);

                    var actions = '<div class="btn-group">' + viewBtn +
                        '             <button data-toggle="dropdown" class="btn btn-primary btn-xs dropdown-toggle">' +
                        '               <span class="caret"></span>' +
                        '             </button>' +
                        '                  <ul class="dropdown-menu">' +
                                           updateBtn + delBtn + testBtn + pushBtn
                        '                  </ul>' +
                        '           </div>';
                    actions = actions.replaceAll("DATA", data);
				    $(td).html(actions);
                },
                width: '70px'
            }
        ],
        ajax_url: assetUserListUrl,
        columns: [
            {data: "id"}, {data: "hostname"}, {data: "ip"},
            {data: "username"}, {data: "version", orderable: false},
            {data: "date_created", orderable: false},
            {data: "asset", orderable: false}
        ],
        op_html: $('#actions').html(),
        lb_html: onlyLatestEl,
    };
    assetUserTable = jumpserver.initServerSideDataTable(options);
    return assetUserTable
}
$(document).ready(function(){
})
.on('click', '.btn-view-auth', function () {
    // 通知给view auth modal
    authAssetId = $(this).data("asset");
    authHostname = $(this).data("hostname");
    authUsername = $(this).data('username');
    authUid = $(this).data("uid");
    if (!mfaNeedCheck){
        $("#asset_user_auth_view").modal('show');
        return
    }
    var now = new Date();
    var nowTime = now.getTime() / 1000;
    if ( !lastMFATime || nowTime - lastMFATime > mfaVerifyTTL ) {
        mfaFor = "viewAuth";
        $("#mfa_auth_confirm").modal("show");
    } else {
        $("#asset_user_auth_view").modal('show');
    }
})
.on("success", '#mfa_auth_confirm', function () {
    if (mfaFor !== "viewAuth") {
        return
    }
    $("#asset_user_auth_view").modal("show");
})
.on('click', '.btn-update-auth', function() {
    authUsername = $(this).data("username") ;
    authHostname = $(this).data("hostname");
    authAssetId = $(this).data("asset");
    $("#asset_user_auth_update_modal").modal('show');
})
.on("click", '.btn-test-auth', function () {
    authUid = $(this).data('uid');
    var theUrl = "{% url 'api-assets:asset-user-task-create'%}?id={{ DEFAULT_PK }}"
        .replace("{{ DEFAULT_PK }}", authUid);

    var success = function (data) {
        var taskId = data.task;
        showCeleryTaskLog(taskId);
    };
    requestApi({
        url: theUrl,
        method: 'POST',
        data: JSON.stringify({action: 'test'}),
        success: success,
        flash_message: false
    });
})
.on('click', '.btn-del-auth', function () {
    var uid = $(this).data("uid");
    var theUrl = defaultAssetUserDetail.replace("{{ DEFAULT_PK }}", uid);
    requestApi({
        url: theUrl,
        method: "DELETE",
        success: function () {
            assetUserTable.ajax.reload(null, false);
        },
        success_message: "{% trans 'Delete success' %}"
    })

})
.on("change", '#only_latest', function () {
    var checked = $("#only_latest").is(":checked");
    if (checked === onlyLatestChecked) {
        return
    }
    var ajaxUrl = assetUserTable.ajax.url();
    if (checked) {
        ajaxUrl = setUrlParam(ajaxUrl, 'latest', 1)
    } else {
        ajaxUrl = setUrlParam(ajaxUrl, 'latest', 0)
    }
    onlyLatestChecked = !onlyLatestChecked;
    assetUserTable.ajax.url(ajaxUrl);
    assetUserTable.ajax.reload();
})


</script>
